<template>
  <el-tabs v-model="activeTab" class="demo-tabs demo-ruleForm">
    <el-tab-pane v-for="(item, index) in formItems" :key="item.id" :label="item.name" :name="item.id.toString()">
      <el-form :model="drugInfo[index]" label-width="100px" :rules="rules" :size="formSize" v-if="drugInfo" ref="forms"
        :disabled="isFormDisabled">
        <el-form-item label="状态:" prop="status">
          <el-radio-group v-model="drugInfo[index].status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="2">下架</el-radio>
            <el-radio :value="3">关闭</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="定时关闭:">
          <div>
            <el-date-picker v-model="drugInfo[index].closeTime" type="datetimerange" start-placeholder="请选择开始时间"
              end-placeholder="请选择结束日期" format="YYYY-MM-DD HH:mm" date-format="YYYY/MM/DD ddd"
              value-format="YYYY-MM-DD HH:mm" clearable time-format="A hh:mm:00" class="custom-date-picker" />
          </div>
          <span class="smTip">(支持到整点)</span>
        </el-form-item>

        <el-form-item label="关闭提示语:" prop="close_tips">
          <el-input v-model="drugInfo[index].close_tips" placeholder="请输入关闭提示语,最多40字" type="text" maxlength="40"
            show-word-limit />
        </el-form-item>

        <el-form-item label="是否提示颗粒剂国/省标倍数:" prop="standard_tips" v-if="item.id == 2">
          <el-radio-group v-model="drugInfo[index].standard_tips">
            <el-radio :value="0">是</el-radio>
            <el-radio :value="1">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="药房对外展示名称:">
          <el-input v-model="drugInfo[index].show_name" placeholder="请输入药房对外展示名称" />
        </el-form-item>

        <el-form-item label="请选择特殊煎煮:" v-if="item.had_decoction == 1">
          <div>
            <el-checkbox-group v-model="drugInfo[index].drug_decoction_id">
              <el-checkbox v-for="(itemDecoctions, indexDecoctions) in formItems[index].drug_decoctions"
                :key="itemDecoctions.id" :label="itemDecoctions.id">
                {{ itemDecoctions.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>

        <el-form-item label=" " v-if="item.had_decoction == 1">
          <div class="tip">特殊煎煮额外收取加工费用<el-input v-model="drugInfo[index].decoction_fee" style="width: 160px;"
              @blur="handleInput(index, '','','decoctionFee', $event)" /> 元/剂
          </div>
        </el-form-item>

        <el-form-item label="请选择加工方式:" class="machiningAll" v-if="item.had_process == 1">
          <el-checkbox-group v-model="drugInfo[index].drugstore_processAll">
            <div class="content" v-for="(itemProcesses, indexProcesses) in formItems[index].drug_processes"
              :key="indexProcesses">
              <div class="header" @click="toggleCollapse(index, indexProcesses)">
                <el-checkbox :value="itemProcesses.id" :label="itemProcesses.name" @click.stop />
                <img class="rightIcon" src="/src/assets/right.png" alt="">
              </div>
              <div v-if="formItems[index].openIndex === indexProcesses" class="collapse">
                <!-- <Form :processes="formItems[index].drug_processes" @processChange="handleProcessChange"></Form> -->
                <el-form-item label="是否展示预计出药时间:">
                  <el-radio-group v-model="drugInfo[index].drugstore_process[indexProcesses].delivery_time_show">
                    <el-radio :value="1">是</el-radio>
                    <el-radio :value="2">否</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="起做量设置:" style="width: 400px;">
                  <el-input class="rightInput" v-model="drugInfo[index].drugstore_process[indexProcesses].min_use"
                    placeholder="请输入起做量" @blur="handleInput(index, indexProcesses,'','minUse', $event)" />克
                </el-form-item>

                <el-form-item label="加工费用设置:" class="machining">
                  <el-radio-group v-model="drugInfo[index].drugstore_process[indexProcesses].fee_type"
                    style="display: flex;flex-flow: column nowrap;align-items: flex-start;">
                    <el-radio :label="1">常用计价 </el-radio>
                    <div v-if="drugInfo[index].drugstore_process[indexProcesses].fee_type == '1'" class="title">
                      <div class="row">
                        <div class="subtitle">起始价格： </div><el-input
                          v-model="drugInfo[index].drugstore_process[indexProcesses].initial_quantity"
                          @blur="handleInput(index, indexProcesses, processIndex,'initial', $event)"
                          placeholder="请输入克数" />克<el-input
                          v-model="drugInfo[index].drugstore_process[indexProcesses].start_price"
                          @blur="handleInput(index, indexProcesses, processIndex,'startprice', $event)"
                          placeholder="请输入价格" />元
                      </div>
                      <div class="row">
                        <div class="subtitle">超出部分价格： </div><el-input
                          v-model="drugInfo[index].drugstore_process[indexProcesses].exceed_quantity"
                          @blur="handleInput(index, indexProcesses, processIndex,'exceed', $event)"
                          placeholder="每超出的克数" />克<el-input
                          v-model="drugInfo[index].drugstore_process[indexProcesses].exceed_price"
                          @blur="handleInput(index, indexProcesses, processIndex,'exceedprice', $event)"
                          placeholder="请输入价格" />元
                      </div>
                    </div>
                    <el-radio :label="2">阶梯计价</el-radio>
                    <div v-if="drugInfo[index].drugstore_process[indexProcesses].fee_type == '2'" class="title">
                      <div class="row"
                        v-for="(process, processIndex) in drugInfo[index].drugstore_process[indexProcesses].fee_detail"
                        :key="processIndex">
                        <div>
                          <el-input v-model="process.min" disabled />g至
                        </div>
                        <div>
                          <el-input v-model="process.max"
                            @blur="handleInput(index, indexProcesses, processIndex,'max', $event)"
                            :disabled="processIndex == drugInfo[index].drugstore_process[indexProcesses].fee_detail.length - 1?false:true" />g
                          <div class="smTip" v-if="!process.isStatus">不能小于前面克数</div>
                        </div>
                        <div>
                          <el-input v-model="process.price"
                            @blur="handleInput(index, indexProcesses, processIndex,'price', $event)" />元
                          <div class="smTip" v-if="!process.isStatusP">请输入价格</div>
                        </div>
                        <img src="/src/assets/delete.png" @click="deleteDomain(index,indexProcesses,processIndex)"
                          v-if="processIndex>0" style="width:20px;height:20px;margin: 10px 6px 0 6px;">
                      </div>
                      <el-button type="primary" @click="addDomain(index,indexProcesses)">新增</el-button>
                    </div>
                    <div v-if="drugInfo[index].drugstore_process[indexProcesses].fee_type == '2'">2</div>
                    <el-radio :label="3">按剂计价</el-radio>
                    <div v-if="drugInfo[index].drugstore_process[indexProcesses].fee_type == '3'" class="title">
                      <div>
                        每剂： <el-input v-model="drugInfo[index].drugstore_process[indexProcesses].agent_price" />元
                      </div>
                    </div>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="加工费成本:" style="width: 400px;">
                  <el-input class="rightInput" v-model="drugInfo[index].drugstore_process[indexProcesses].cook_cost"
                    @blur="handleInput(index, indexProcesses,'','cookCost', $event)" /><span>元</span>
                </el-form-item>

                <el-form-item label="请选择辅料:">
                  <!-- drugInfo[index].drugstore_process[indexProcesses].drug_auxiliary -->
                  <!-- <el-radio-group v-model="drugInfo[index].drugstore_process[indexProcesses].drug_auxiliary">
                      <el-radio v-for="(accessoriesItem,accessoriesIndex) in  accessoriesItem" :key="accessoriesIndex"
                        :value="accessoriesItem.id">{{accessoriesItem.name}}</el-radio>
                    </el-radio-group> -->
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox label="无" value="1" />
                  </el-checkbox-group>

                </el-form-item>

                <el-form-item label="用法用量:" v-if="item.id == 1 || item.id == 2"
                  :prop="'drugstore_process[' + indexProcesses + '].usage_id'"
                  :rules="rules.usage_id(index, indexProcesses)">
                  <el-checkbox-group v-model="drugInfo[index].drugstore_process[indexProcesses].usage_id">
                    <el-checkbox name="type" v-for="(itemUsage,indexUsage) in dosageItems" :key="indexUsage"
                      :value="itemUsage.id" :label="itemUsage.name" />
                  </el-checkbox-group>
                </el-form-item>

                <el-form-item label="药房说明:" :prop="'drugstore_process[' + indexProcesses + '].drugstore_remark'"
                  :rules="rules.drugstore_remark(index, indexProcesses)">
                  <el-input v-model="drugInfo[index].drugstore_process[indexProcesses].drugstore_remark"
                    placeholder="请输入" />
                </el-form-item>

                <el-form-item label="特殊提示:">
                  <el-input v-model="drugInfo[index].drugstore_process[indexProcesses].remark" type="textarea"
                    maxlength="200" show-word-limit placeholder="医生开方时的特殊提示.(比如,请确认患者是否为糖尿病患者) 若无可不填写" />
                </el-form-item>

                <el-form-item label="代煎/自煎设置:" :prop="'drugstore_process[' + indexProcesses + '].patient_is_allow'"
                  :rules="rules.patient_is_allow(index, indexProcesses)">
                  <el-radio-group v-model="drugInfo[index].drugstore_process[indexProcesses].patient_is_allow">
                    <el-radio :value="1">允许患者自行选择代煎/自煎</el-radio>
                    <el-radio :value="2">仅允许自煎</el-radio>
                    <el-radio :value="3">仅允许代煎</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="患者端提示文案:">
                  <el-input
                    :disabled="drugInfo[index].drugstore_process[indexProcesses].patient_is_allow == '2' || drugInfo[index].drugstore_process[indexProcesses].patient_is_allow == '3'?true:false"
                    v-model="drugInfo[index].drugstore_process[indexProcesses].patient_desc" />
                </el-form-item>

                <el-form-item label="快递设置:">
                  <el-radio-group v-model="drugInfo[index].drugstore_process[indexProcesses].express_type"
                    style="display: flex;flex-flow: column nowrap;align-items: flex-start;">
                    <el-radio :value="1">包邮</el-radio>
                    <el-radio :value="4">不包邮（到付）</el-radio>
                  </el-radio-group>
                </el-form-item>

              </div>
            </div>
          </el-checkbox-group>
          <div class="smTip" v-if="drugInfo[index].is_drugstore_processAll ==  true">
            至少选择一个加工方式
          </div>
        </el-form-item>

        <div style="font-size:14px;color:#606266;"><span class="smTip">*</span>药房人员配置:<span
            class="smTip">(为了处方的合规性，请您务必填写真实人员的姓名。)</span></div>


        <div class="row bottomInput">
          <el-form-item label="药房审核人员：" prop="drugstore_worker.audit_name">
            <el-input type="text" v-model="drugInfo[index].drugstore_worker.audit_name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="审核人员联系方式">
            ：<el-input v-model="drugInfo[index].drugstore_worker.audit_mobile" placeholder="请输入联系方式" />
          </el-form-item>
          <el-form-item label="审核人员签名：">

            <el-upload class="avatar-uploader" :show-file-list="false"
              :http-request="e => fileUpload(e, 'audit_sign',index)">
              <img v-if="drugInfo[index].drugstore_worker.audit_sign" :src="drugInfo[index].drugstore_worker.audit_sign"
                class="avatar">
              <div class="upLoadImg" v-else>
                <img class="addImg" src="/src/assets/addIm%20g.png" alt="">
                <div class="titles">上传图片</div>
              </div>
            </el-upload>
          </el-form-item>
        </div>

        <div class="row bottomInput">
          <el-form-item label="药房调配人员：" prop="drugstore_worker.deploy_name">
            <el-input type="text" v-model="drugInfo[index].drugstore_worker.deploy_name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="调配人员联系方式">
            ：<el-input v-model="drugInfo[index].drugstore_worker.deploy_mobile" placeholder="请输入联系方式" />
          </el-form-item>
          <el-form-item label="调配人员签名：">

            <el-upload class="avatar-uploader" :show-file-list="false"
              :http-request="e => fileUpload(e, 'deploy_sign',index)">
              <img v-if="drugInfo[index].drugstore_worker.deploy_sign"
                :src="drugInfo[index].drugstore_worker.deploy_sign" class="avatar">
              <div class="upLoadImg" v-else>
                <img class="addImg" src="/src/assets/addIm%20g.png" alt="">
                <div class="titles">上传图片</div>
              </div>
            </el-upload>
          </el-form-item>
        </div>

        <div class="row bottomInput">
          <el-form-item label="药房核对人员：" prop="drugstore_worker.check_name">
            <el-input v-model="drugInfo[index].drugstore_worker.check_name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="核对人员联系方式">
            ：<el-input v-model="drugInfo[index].drugstore_worker.check_mobile" placeholder="请输入联系方式" />
          </el-form-item>
          <el-form-item label="核对人员签名：">

            <el-upload class="avatar-uploader" :show-file-list="false"
              :http-request="e => fileUpload(e, 'check_sign',index)">
              <img v-if="drugInfo[index].drugstore_worker.check_sign" :src="drugInfo[index].drugstore_worker.check_sign"
                class="avatar">
              <div class="upLoadImg" v-else>
                <img class="addImg" src="/src/assets/addIm%20g.png" alt="">
                <div class="titles">上传图片</div>
              </div>
            </el-upload>
          </el-form-item>
        </div>




        <div class="row bottomInput">
          <el-form-item label="药房发药人员：" prop="drugstore_worker.allocate_name">
            <el-input v-model="drugInfo[index].drugstore_worker.allocate_name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="发药人员联系方式：">
            ：<el-input v-model="drugInfo[index].drugstore_worker.allocate_mobile" placeholder="请输入联系方式" />
          </el-form-item>
          <el-form-item label="发药人员签名：">

            <el-upload class="avatar-uploader" :show-file-list="false"
              :http-request="e => fileUpload(e, 'allocate_sign',index)">
              <img v-if="drugInfo[index].drugstore_worker.allocate_sign"
                :src="drugInfo[index].drugstore_worker.allocate_sign" class="avatar">
              <div class="upLoadImg" v-else>
                <img class="addImg" src="/src/assets/addIm%20g.png" alt="">
                <div class="titles">上传图片</div>
              </div>
            </el-upload>
          </el-form-item>
        </div>

      </el-form>
    </el-tab-pane>
  </el-tabs>

</template>

<script setup>
  const qiniuParseUrl = String(import.meta.env.VITE_QINIU_PARSE_URL)
  const emit = defineEmits(['updateForm'])
  import {
    listUnite,
    detailShow
  } from '/src/api/pharmacy/basis'
  import {
    list
  } from '/src/api/drug/usageDosage'
  import {
    token as qiniuTokenApi
  } from "@/api/common"
  import * as qiniu from 'qiniu-js'
  import {
    ElMessage
  } from "element-plus";

  import {
    ref,
    watch,
    defineProps,
    onMounted,
    nextTick,
    reactive
  } from 'vue';

  const formSize = ref('default')
  const qiniuToken = ref("")
  const options = {
    quality: 1,
    noCompressIfLarger: true
  }
  const props = defineProps({
    activeName: String,
    editId: String,
    isFormDisabled: Boolean
  });

  const checkList = ref(['1'])
  const closeTime = ref('')

  const formItems = ref([]);
  const drugInfo = ref([])
  const requestDataAll = ref({})
  const getListUnite = async () => {
    const result = await listUnite();
    formItems.value = result.data
    if (formItems.value.length > 0) {
      drugInfo.value = formItems.value.map(item => ({
        close_tips: "",
        close_end_time: "",
        close_start_time: "",
        status: 1,
        standard_tips: 0,
        drug_type_id: item.id,
        drug_type_name: item.name,
        is_drugstore_processAll: false,
        drugstore_processAll: [],
        drug_decoction_id: [],
        drugstore_worker: {
          audit_name: "",
          audit_mobile: "",
          deploy_name: "",
          deploy_mobile: "",
          check_name: "",
          check_mobile: "",
          allocate_name: "",
          allocate_mobile: ""
        },
        drugstore_process: item.drug_processes.map(process => ({
          drug_process_id: process.id,
          min_use: "",
          initial_quantity: "",
          start_price: "",
          exceed_quantity: "",
          exceed_price: "",
          drug_auxiliary: [],
          remark: "",
          // "checked": true,
          id: process.id,
          name: process.name,
          type_id: item.id,
          usage_id: [],
          delivery_time_show: 1,
          drugstore_remark: "",
          fee_type: "1",
          fee_detail: [{
            min: "0.0",
            max: "",
            price: "",
            isStatus: true,
            isStatusP: true
          }],
          agent_price: "",
          patient_is_allow: null,
          patient_desc: "",
          express_type: "1",
          express_detail: {
            free_price: "",
            no_free_price: "",
          }
        })),

      }));
      if (props.editId) {
        getDetail()
      } else {}
    }
  }


  const activeTab = ref('');
  const dosageItems = ref([])
  const accessoriesItem = ref([])

  //详情
  const getDetail = async () => {
    const result = await detailShow({
      id: props.editId
    });
    if (result.code === 200) {
      // Object.assign(drugInfo, result.data.drugInfo);
      drugInfo.value = result.data.drugInfo
      const newDrugInfo = drugInfo.value.map(item => {
        // 在这里插入新的键名和参数
        return {
          ...item,
          drugstore_processAll: [...item.drugstore_process.map(process => process.drug_process_id)],
          closeTime: [item.close_start_time, item.close_end_time]
        };
      });
      console.log(99, newDrugInfo)
      // if (result.data.baseInfo.close_start_time && result.data.baseInfo.close_end_time) {
      //   closeTime.value = [result.data.baseInfo.close_start_time, result.data.baseInfo.close_end_time]
      // }
      drugInfo.value = newDrugInfo
      console.log(drugInfo.value)
    }
  }

  const getlist = async () => {
    const result = await list();
    dosageItems.value = result.data.data
  }

  const getQiniuToken = async () => {
    const res = await qiniuTokenApi()
    qiniuToken.value = res.data.upToken
  }

  //验证集合
  const rules = reactive({
    ['status']: [{
      required: true,
      trigger: 'submit'
    }],
    ['close_tips']: [{
      required: true,
      message: "请输入关闭提示语",
      trigger: 'submit'
    }],
    ['drugstore_worker.audit_name']: [{
      required: true,
      message: "请输入药房审核员姓名",
      trigger: 'submit'
    }],
    ['standard_tips']: [{
      required: true,
      trigger: 'submit'
    }],

    ['drugstore_worker.deploy_name']: [{
      required: true,
      message: "请输入药房调配员姓名",
      trigger: 'submit'
    }],
    ['drugstore_worker.check_name']: [{
      required: true,
      message: "请输入药房核对员姓名",
      trigger: 'submit'
    }],
    ['drugstore_worker.allocate_name']: [{
      required: true,
      message: "请输入药房发药员姓名",
      trigger: 'submit'
    }],
    usage_id: (index, indexProcesses) => [{
      required: true,
      message: "请选择用法用量",
      trigger: 'submit' // 触发验证的时机，可以根据实际情况调整
    }],
    drugstore_remark: (index, indexProcesses) => [{
      required: true,
      message: "请填写药房说明",
      trigger: 'submit' // 触发验证的时机，可以根据实际情况调整
    }],
    patient_is_allow: (index, indexProcesses) => [{
      required: true,
      message: "请设置代煎/自煎",
      trigger: 'submit' // 触发验证的时机，可以根据实际情况调整
    }]
  });

  onMounted(() => {
    nextTick(() => {
      getListUnite()
      getQiniuToken()
      getlist()

    })
  })

  const getCloseTime = (value, id) => {
    // 检查索引是否在 baseInfo 数组的范围内
    if (value) {
      drugInfo.value[id].close_start_time = value[0] ? value[0] : '';
      drugInfo.value[id].close_end_time = value[1] ? value[1] : '';
    }
  }


  // ref存到数组
  const getRiskSpreadRef = ref([])

  const fileUpload = (e, prop, index) => {
    console.log(e)
    const file = e.file;
    if (!file) return;

    const fileName = file.name; // 获取文件名
    const fileExtension = fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2); // 提取文件扩展名

    qiniu.compressImage(e.file, options).then(data => {
      const key = `images/${prop}/${new Date().getTime()}.${fileExtension}`;
      const config = {}
      const putExtra = {}
      const observer = {
        next(res) {
          // 上传过程中的状态信息
          console.log(res.total.percent);
        },
        error(err) {
          console.log(err);
        },
        complete(res) {

          console.log('qiniuParseUrl', qiniuParseUrl, prop, index)
          drugInfo.value[index].drugstore_worker[prop] = qiniuParseUrl + "/" + key
          console.log(drugInfo.value)

        }
      }
      const observable = qiniu.upload(data.dist, key, qiniuToken.value, putExtra, config)
      const subscription = observable.subscribe(observer)
    })
  }
  const deleteDomain = (index, indexProcesses, index2) => {
    console.log(index, indexProcesses, index2)
    console.log(drugInfo.value[index].drugstore_process[indexProcesses].fee_detail)
    drugInfo.value[index].drugstore_process[indexProcesses].fee_detail = drugInfo.value[index].drugstore_process[
      indexProcesses].fee_detail.filter((item, index) => index != index2);
  }
  //阶梯计价add方法
  const addDomain = (index, indexProcesses) => {
    const getMinIndex = drugInfo.value[index].drugstore_process[indexProcesses].fee_detail.length - 1
    if (drugInfo.value[index].drugstore_process[indexProcesses].fee_detail[getMinIndex].max) {
      drugInfo.value[index].drugstore_process[indexProcesses].fee_detail[getMinIndex].isStatus = true
    }
    if (drugInfo.value[index].drugstore_process[indexProcesses].fee_detail[getMinIndex].price) {
      drugInfo.value[index].drugstore_process[indexProcesses].fee_detail[getMinIndex].isStatusP = true
    }
    if (drugInfo.value[index].drugstore_process[indexProcesses].fee_detail[getMinIndex].max && drugInfo.value[index]
      .drugstore_process[indexProcesses].fee_detail[getMinIndex].price) {
      if (drugInfo.value[index].drugstore_process[indexProcesses].fee_detail[getMinIndex].isStatus) {
        drugInfo.value[index].drugstore_process[indexProcesses].fee_detail.push({
          min: toFixedNoRounding(Number(drugInfo.value[index].drugstore_process[indexProcesses].fee_detail[
            getMinIndex].max) + 0.1),
          max: '',
          price: '',
          isStatus: true,
          isStatusP: true
        })
      } else {
        ElMessage.error('请完善后再添加.')
      }
    } else {
      ElMessage.error('请完善后再添加.')
      if (!drugInfo.value[index].drugstore_process[indexProcesses].fee_detail[getMinIndex].max) {
        drugInfo.value[index].drugstore_process[indexProcesses].fee_detail[getMinIndex].isStatus = false
      }
      if (!drugInfo.value[index].drugstore_process[indexProcesses].fee_detail[getMinIndex].price) {
        drugInfo.value[index].drugstore_process[indexProcesses].fee_detail[getMinIndex].isStatusP = false
      }
    }

  }

  const handleInput = (index1, index2, index3, type, event) => {
    if (type == "max") {
      const value = drugInfo.value[index1].drugstore_process[index2].fee_detail[index3].max
      const parsedValue = parseFloat(value);
      if (!isNaN(parsedValue)) {
        drugInfo.value[index1].drugstore_process[index2].fee_detail[index3].max = toFixedNoRounding(parsedValue) + '';
        if (Number(toFixedNoRounding(parsedValue)) > Number(drugInfo.value[index1].drugstore_process[index2]
            .fee_detail[
              index3].min)) {
          drugInfo.value[index1].drugstore_process[index2].fee_detail[index3].isStatus = true
        } else {
          drugInfo.value[index1].drugstore_process[index2].fee_detail[index3].isStatus = false
        }
      } else {
        drugInfo.value[index1].drugstore_process[index2].fee_detail[index3].max = '';
      }
    } else if (type == "price") {
      const value = drugInfo.value[index1].drugstore_process[index2].fee_detail[index3].price;
      const parsedValue = parseFloat(value);
      if (!isNaN(parsedValue)) {
        // 如果输入值是合法的数字，则保留一位小数
        drugInfo.value[index1].drugstore_process[index2].fee_detail[index3].isStatusP = true
        drugInfo.value[index1].drugstore_process[index2].fee_detail[index3].price = toFixedNoRounding(parsedValue);
      } else {
        // 如果输入值不是合法的数字，则清空输入值
        drugInfo.value[index1].drugstore_process[index2].fee_detail[index3].isStatusP = false
        drugInfo.value[index1].drugstore_process[index2].fee_detail[index3].price = '';
      }
    } else if (type == "initial") {
      const value = drugInfo.value[index1].drugstore_process[index2].initial_quantity;
      const parsedValue = parseFloat(value);
      if (!isNaN(parsedValue)) {
        // 如果输入值是合法的数字，则保留一位小数
        drugInfo.value[index1].drugstore_process[index2].initial_quantity = toFixedNoRounding(parsedValue);
      } else {
        // 如果输入值不是合法的数字，则清空输入值
        drugInfo.value[index1].drugstore_process[index2].initial_quantity = '';
      }
    } else if (type == "startprice") {
      const value = drugInfo.value[index1].drugstore_process[index2].start_price;
      const parsedValue = parseFloat(value);
      if (!isNaN(parsedValue)) {
        // 如果输入值是合法的数字，则保留一位小数
        drugInfo.value[index1].drugstore_process[index2].start_price = toFixedNoRounding(parsedValue);
      } else {
        // 如果输入值不是合法的数字，则清空输入值
        drugInfo.value[index1].drugstore_process[index2].start_price = '';
      }
    } else if (type == "exceed") {
      const value = drugInfo.value[index1].drugstore_process[index2].exceed_quantity;
      const parsedValue = parseFloat(value);
      if (!isNaN(parsedValue)) {
        // 如果输入值是合法的数字，则保留一位小数
        drugInfo.value[index1].drugstore_process[index2].exceed_quantity = toFixedNoRounding(parsedValue);
      } else {
        // 如果输入值不是合法的数字，则清空输入值
        drugInfo.value[index1].drugstore_process[index2].exceed_quantity = '';
      }
    } else if (type == "exceedprice") {
      const value = drugInfo.value[index1].drugstore_process[index2].exceed_price;
      const parsedValue = parseFloat(value);
      if (!isNaN(parsedValue)) {
        // 如果输入值是合法的数字，则保留一位小数
        drugInfo.value[index1].drugstore_process[index2].exceed_price = toFixedNoRounding(parsedValue);
      } else {
        // 如果输入值不是合法的数字，则清空输入值
        drugInfo.value[index1].drugstore_process[index2].exceed_price = '';
      }
    } else if (type == "cookCost") {
      const value = drugInfo.value[index1].drugstore_process[index2].cook_cost;
      const parsedValue = parseFloat(value);
      if (!isNaN(parsedValue)) {
        // 如果输入值是合法的数字，则保留一位小数
        drugInfo.value[index1].drugstore_process[index2].cook_cost = toFixedNoRounding(parsedValue);
      } else {
        // 如果输入值不是合法的数字，则清空输入值
        drugInfo.value[index1].drugstore_process[index2].cook_cost = '';
      }
    } else if (type == 'minUse') {
      const value = drugInfo.value[index1].drugstore_process[index2].min_use;
      const parsedValue = parseFloat(value);
      if (!isNaN(parsedValue)) {
        // 如果输入值是合法的数字，则保留一位小数
        drugInfo.value[index1].drugstore_process[index2].min_use = toFixedNoRounding(parsedValue);
      } else {
        // 如果输入值不是合法的数字，则清空输入值
        drugInfo.value[index1].drugstore_process[index2].min_use = '';
      }
    } else if (type == 'decoctionFee') {
      const value = drugInfo.value[index1].decoction_fee;
      const parsedValue = parseFloat(value);
      if (!isNaN(parsedValue)) {
        // 如果输入值是合法的数字，则保留一位小数
        drugInfo.value[index1].decoction_fee = toFixedNoRounding(parsedValue);
      } else {
        // 如果输入值不是合法的数字，则清空输入值
        drugInfo.value[index1].decoction_fee = '';
      }
    }

  }


  const toFixedNoRounding = (num) => {
    const strNum = num.toString();
    const indexDot = strNum.indexOf('.');
    if (indexDot === -1) {
      // 整数，补充一个0后面
      return num.toFixed(1);
    } else {
      // 已有小数点，直接取整
      return Math.floor(num * 10) / 10;
    }
  }


  const changeInput = (e) => {
    if (e.target.value.indexOf(".") >= 0) {
      e.target.value = e.target.value.substring(
        0,
        e.target.value.indexOf(".") + 2
      );
    }
  }

  watch(() => props.activeName, (newValue) => {
    activeTab.value = formItems.value[0].id.toString();
  });

  const toggleCollapse = (index, indexProcesses) => {
    if (!drugInfo.value[index].drugstore_process) {
      drugInfo.value[index].drugstore_process = [];
    }
    if (event.target.tagName.toLowerCase() === 'input') {
      // 点击的是 el-checkbox，处理勾选逻辑
      const idToAdd = formItems.value[index].drug_processes[indexProcesses].id;
      const indexInDrugstoreProcess = drugInfo.value[index].drugstore_process.findIndex(item => item.id ===
        idToAdd);
      if (indexInDrugstoreProcess !== -1) {
        drugInfo.value[index].drugstore_process.splice(indexInDrugstoreProcess, 1);
      } else {
        drugInfo.value[index].drugstore_process.push({
          id: idToAdd
        });
      }
    } else {
      // 点击的是 header，处理展开/关闭逻辑
      formItems.value[index].openIndex = formItems.value[index].openIndex === indexProcesses ? null :
        indexProcesses;
    }
  };

  const handleProcessChange = (selectedProcess, index) => {
    drugInfo[index].drugstore_process = selectedProcess;
  }

  const submitForm = async () => {
    try {
      // 循环验证所有表单
      const isValid = await validateForms();
      console.log('我看的', drugInfo.value)
      if (isValid) {
        //验证通过
        const submit = {
          ...drugInfo
        }
        const requestData = drugInfo.value
        requestData.forEach((item, index) => {
          if (item.closeTime && Array.isArray(item.closeTime) && item.closeTime.length >= 2) {
            item.close_start_time = item.closeTime[0];
            item.close_end_time = item.closeTime[1];
            delete item.closeTime;
          }
        });

        const newrequestData = requestData.map((item, index) => {
          const filteredIds = item.drugstore_processAll;
          const filteredData = props.editId ? item.drugstore_process.filter(process => filteredIds.includes(
            process.drug_process_id)) : item.drugstore_process.filter(process => filteredIds.includes(process
            .id));

          const exceed_quantity = item.drugstore_process.map(process => process.exceed_quantity.toString());
          const exceed_price = item.drugstore_process.map(process => process.exceed_price.toString());

          return {
            ...item,
            drugstore_process: filteredData,
            exceed_quantity: exceed_quantity,
            exceed_price: exceed_price
          };
        });



        console.log('newrequestData', newrequestData)
        requestDataAll.value = newrequestData
      } else {
        // 验证不通过，输出错误信息
        console.log('error submit!2')
        drugInfo.value.forEach((item, index) => {
          if (item.drugstore_processAll.length === 0) {
            // 如果没有选择加工方式，输出错误信息
            drugInfo.value[index].is_drugstore_processAll = true
          } else {
            // 选择了加工方式，执行提交操作
            console.log('提交成功', item);
            drugInfo.value[index].is_drugstore_processAll = false
            // 这里可以调用提交表单的函数
            // 比如：this.submitForm(item);
          }
        });

      }
    } catch (error) {
      // 处理错误
      console.error('出现错误：', error);
    }
  }


  const forms = ref(null); // 表单的引用
  const validateForms = async () => {
    // 初始化验证结果
    let isValid = true;
    let hasError = false; // 标记是否存在药品未选择加工方式

    // 收集每个表单的验证 Promise
    const validatePromises = forms.value.map(form => new Promise(resolve => {
      form.validate((valid) => {
        // 如果有任何一个表单验证失败，则将 isValid 设置为 false
        if (!valid) {
          isValid = false;
          console.log('表单验证失败');
        }
        resolve();
      });
    }));

    // 等待所有表单的验证结果完成
    await Promise.all(validatePromises);

    // 检查是否每个药品至少选择了一种加工方式
    drugInfo.value.forEach(item => {
      if (item.drugstore_processAll.length === 0) {
        // 如果有药品没有选择加工方式，将验证结果设置为失败
        isValid = false;
        // 设置标记为 true
        hasError = true;
      }
    });

    // 只在有药品未选择加工方式时提示错误信息
    if (hasError) {
      ElMessage.error('每个药品至少选择一种加工方式.');
    }

    return isValid;
  };





  defineExpose({
    async submitFormWithResultD() {
      await submitForm(); // 假设这是你的 submitForm 方法
      return requestDataAll.value; // 返回子组件的结果
    }
  });
</script>
<style lang="scss" scoped>
  ::v-deep .el-collapse-item__header {
    background: #f6faff !important;
    padding: 0px 15px;
    color: #373737;
  }

  ::v-deep .el-collapse-item__content {
    padding: 20px 40px;
  }

  ::v-deep .el-checkbox-group {
    width: 100%;
  }

  ::v-deep .el-input {
    width: 86%;
  }

  ::v-deep .el-form-item__label {
    width: 180px !important;
  }


  .header {
    background: #f6faff;
    padding: 6px 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
  }

  .rightIcon {
    width: 16px;
    height: 16px;
  }

  .collapse {
    padding: 10px 14px;
    width: 89%;
    border: 1px solid #e4eaf0;
    margin-top: 12px;
    border-radius: 4px;
    // display: none;
    // background: #f9b3cc;
  }

  .collapse ::v-deep .el-form-item {
    margin-bottom: 24px;
    ;
  }

  .nocollapse {
    display: none;
  }

  .title {
    color: #606266;
    font-size: 14px;
    padding: 10px 15px;
    // background: #f6faff;
    // width: 460px;
  }

  .title ::v-deep .el-input {
    width: 100px;
    margin-left: 4px;
    margin-right: 8px;
  }

  .tip {
    font-size: 14px;
    color: #606266;
  }

  .tip ::v-deep .el-input {
    margin: 0 6px;
  }

  ::v-deep .el-checkbox {
    font-weight: 400 !important;
  }

  ::v-deep .el-radio {
    font-weight: 400 !important;
  }

  .demo-tabs {
    width: 96%;
    max-width: 1000px;
    margin: 0 auto;
  }

  .machining ::v-deep .el-collapse-item__content {
    padding: 20px 40px;
  }

  .machining ::v-deep .el-checkbox-group {
    width: 100%;
  }


  .machining .title {
    color: #606266;
    font-size: 14px;
    padding: 10px 15px;
    background: #f6faff;
    // width: 460px;
    margin: 12px 0
  }

  .allocation {
    margin-bottom: 12px;
    display: flex;
    justify-content: space-between;
  }

  .allocation ::v-deep .el-input {
    width: 160px;
    height: 34px;
  }

  .title .subtitle {
    width: 100px;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
  }

  ::v-deep .el-radio {
    font-weight: 400 !important;
  }

  .machiningAll ::v-deep .el-form-item {
    margin: 12px 0;
  }

  .row {
    display: flex;
    flex-direction: row;
    margin: 12px 0;
  }

  .rightInput {
    margin-right: 6px;
  }

  .leftInput {
    margin-left: 6px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar-uploader img {
    width: 120px;
    height: auto;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  //上传的样式
  .upLoadImg {
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    padding: 6px 8px;
    text-align: center;
    width: 120px;

    .titles {
      font-size: 12px;
      color: #8c939d;
    }

    .addImg {
      width: 40px;
      height: 40px;
    }
  }

  .smTip {
    color: #e02020;
    font-size: 12px;
    margin-left: 12px;
  }

  /* 修改提示语颜色 */
  ::v-deep .el-range-input::placeholder {
    color: #b6bcc4;
    font-size: 12px;
  }

  .demo-ruleForm {
    padding: 20px 40px;
  }

  ::v-deep .el-form-item {
    margin-bottom: 20px;
  }

  ::v-deep .el-radio {
    font-weight: 400 !important;
  }

  ::v-deep .el-tab-pane {
    // width:860px;
    min-width: 860px;
  }

  .bottomInput ::v-deep .el-form-item__content {
    align-items: center;
    display: flex;
    flex: 1;
    flex-wrap: wrap;
    font-size: var(--font-size);
    // line-height: 32px;
    min-width: 0;
    position: relative;
    align-content: flex-start;
  }
</style>